# -*- coding: utf-8 -*-
# @时间：2023/11/2 20:57
# @作者：CJiaの可乐哥
# @文件名：user
# @软件：Pycharm2023
from typing import List

from django.shortcuts import get_object_or_404
from ninja import Field, ModelSchema, Query, Router, Schema
from ninja.pagination import paginate

from system.models import Users, UserRole, UserPost, Dept, RolePermission, RoleDept
from utils.cj_ninja import MyPagination
from utils.cj_curd import retrieve, status, update, delete
from utils.usual import get_user_info
from utils.cj_response import ErrorResponse

router = Router()


class Filters(Schema):
    id: int = Field(None, alias="id")
    name: str = Field(None, alias="name")
    mobile: str = Field(None, alias="mobile")
    status: bool = Field(None, alias="status")


class UserSchemaIn(ModelSchema):
    posts: list = []
    roles: list = []

    class Config:
        model = Users
        model_exclude = ['id', 'is_superuser', 'password', 'sort',
                         'create_datetime', 'update_datetime']


class UserSchemaOut(ModelSchema):
    roles: list = []
    posts: list = []

    class Config:
        model = Users
        model_exclude = ['password']


@router.delete("/user/{user_id}")
def delete_user(request, user_id: int):
    return ErrorResponse(msg="删除不了一点")


@router.put("/user/status/{user_id}")
def status_user(request, user_id: int):
    request.types = "sys:user:update"
    # 调用修改状态方法
    result = "用户暂不支持禁用"
    # 返回结果
    return ErrorResponse(msg=result)


@router.put("/user/{user_id}", response=UserSchemaOut)
def update_user(request, user_id: int, data: UserSchemaIn):
    request.types = "sys:menu:update"
    # 调用修改方法
    result = update(request, user_id, data, Users)
    # 返回结果
    return get_user_info(result.id)


@router.get("/user/{user_id}", response=UserSchemaOut)
def get_user(request, user_id: int):
    user = get_user_info(user_id)
    return user


@router.get("/user", response=List[UserSchemaOut])
@paginate(MyPagination)
def list_user(request, filters: Filters = Query(...)):
    qs = retrieve(request, Users, filters)
    users = []
    for q in qs:
        user = get_user_info(q.id)
        users.append(user)
    return users
